<template>
    <div @click="treeBlurHide" class="mc-wrapper">
        <el-form v-model="filter" label-position="top" :inline="true"  class="">
            <el-row>
                <el-col :span="4">
                    <el-form-item label="客户类别: ">
                        <el-input v-model="category.name" icon="caret-bottom" placeholder="请选择客户类别"  size="small"></el-input>
                        <div @click.stop="category.showTree=!category.showTree"
                             style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;">
                            <div v-show="category.showTree" class="department-tree-select inline-tree" >
                                <el-tree :data="category.data"
                                         show-checkbox
                                         default-expand-all
                                         node-key="id"
                                         ref="searchTree"
                                         @check-change="handleCheckChange"
                                         :props="defaultProps">
                                </el-tree>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="呼入次数: ">
                        <el-input v-model.number="filter.times" size="small" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="呼入时间: ">
                        <el-date-picker size="small"
                                v-model="filter.dateRange"
                                type="daterange"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                
            </el-row>
            <el-row>
            	<el-col :span="24" class="action_col">
            		<el-form-item class="action_button_group_open">
		                <el-button @click="clearFilter" type="primary" icon="el-icon-delete" size="small">清空筛选条件</el-button>
		                <el-button @click="missedCallSearch" type="primary" icon="el-icon-search" size="small">查询</el-button>
                	</el-form-item>
            	</el-col>
            </el-row>
        </el-form>

        <el-table :data="missedCall" border style="width: 100%" stripe highlight-current-row>
            <el-table-column prop="callerNum" label="呼入号码" width="" align="center"></el-table-column>
            <el-table-column prop="customerName" label="客户名称" width="" align="center">
                <template scope="scope">
                    <span @click="linkToDetail(scope.row)" :class="{colorBlue: scope.row.userName == user.name}">{{scope.row.customerName}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="typeName" label="客户类别" width="" align="center"></el-table-column>
            <el-table-column prop="userName" label="销售员" width="" align="center"></el-table-column>
            <el-table-column prop="num" label="呼入次数" width="" align="center"></el-table-column>
            <el-table-column prop="maxTime" label="最近一次呼入时间" min-width="160" align="center">
                <template scope="scope">
                    <div>{{scope.row.maxTime | timeFormat}}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="" align="center">
                <template scope="scope">
                    <el-button v-if="isShowCall(scope.row)" @click="callContact(scope.row)" :class="{calling: calling}" type="primary" size="small">回拨</el-button>
                    <el-button @click="callHang" class="call-hang" type="danger" size="small">挂断</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-bar">
            <el-pagination class=""
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="filter.currentPage"
                           :page-sizes="pageSizes"
                           :page-size="filter.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios';
    import { mapGetters } from 'vuex'
    import { Row,Col,Button,Input,DatePicker,FormItem,Form,Table,TableColumn,MessageBox,Message,Icon,Tree,Dialog,Tooltip,Pagination } from 'element-ui'
    import { getLevelName,getDate } from '../../utils/auth'
    import Cookie from 'js-cookie'

    Vue.use(Row)
    Vue.use(Col)
    Vue.use(Button)
    Vue.use(Input)
    Vue.use(DatePicker)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Table)
    Vue.use(TableColumn)
    Vue.use(Icon)
    Vue.use(Tree)
    Vue.use(Dialog)
    Vue.use(Tooltip)
    Vue.use(Pagination);

    Vue.prototype.$message = Message;

    export default {
       head(){
            return {
                title: "未接电话"
            }
        },
        data () {
            return {
                tabName: '未接电话',
                missedCall: [{
                    number: '13886853259',
                    name: 'test',
                    level: '1类',
                    seller: '徐文茹',
                    times: 2,
                    lastCallTime: '2017-05-04'
                }],
                filter: {
                    levels: [],
                    times: null,
                    dateRange: [],
                    currentPage: 1,
                    pageSize:50
                },
                category: {
                    name: '',
                    showTree: false,
                    data:[{
                        id: 0,
                        label: '全部',
                        children: [{    //预留children
                            id: 1,
                            label: '暂无数据'
                        }]
                    }]
                },
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                pageSizes: [10,30,50],
                total: 0,
                user: {id: null},
                calling: false
            }
        },
        computed: {
            ...mapGetters({
                'customerDetailList': 'getCustomerDetailList',
                'pageTabsList': 'getPageTabsList'
            }),
            missedCallParams () {
                let start = this.filter.dateRange[0] != null ? getDate(new Date(this.filter.dateRange[0]),false) : '';
                let end = this.filter.dateRange[1] != null ? getDate(new Date(this.filter.dateRange[1]),false) : '';
                return {
                    start: this.filter.currentPage,
                    size: this.filter.pageSize,
                    uuId: this.user.id,
                    timeAll: this.filter.times,
                    level: this.filter.levels || [],
                    startTime:  start,
                    endTime: end
                }
            }
        },
        filters: {
            timeFormat(value){
                if(value){
                    let d = new Date(value);
                    return getDate(d,true)
                }
            },
        },
        methods: {
            //搜索条件加入cookie
            setFilterCookie(){
                let data = JSON.stringify(this.filter);
                this.$store.commit('MISSED_CALL_FILTER',{data});

                let user = JSON.stringify(this.user);
                this.$store.commit('MISSED_CALL_USER',{data:user});

                let category = JSON.stringify(this.category.name);
                this.$store.commit('MISSED_CALL_CATEGORY',{data:category});
            },
            //客户分类选中回调
            handleCheckChange(data,checked) {
                this.category.name ='';
                var checkedId = this.$refs.searchTree.getCheckedKeys(data,true);
                var checkedName = [];
                if(checkedId.length == this.category.data[0].children.length) {
                    this.category.name = '全部'
                }else {
                    for(var i=0;i<checkedId.length;i++){
                        checkedName.push(getLevelName(checkedId[i]));
                    }
                    this.category.name = checkedName.join(' / ');
                }
                this.filter.levels = checkedId.join(',');
            },
            //隐藏客户分类
            treeBlurHide(){
                this.category.showTree = false;
            },
            handleSizeChange(index) {
                this.filter.pageSize = index;
                this.missedCallSearch();
            },
            handleCurrentChange(index) {
                this.filter.currentPage = index;
                this.missedCallSearch();
            },
            isShowCall(row) {
                if(row.userName == this.user.name || row.customerId == null) {
                    return true
                }else {
                    return false
                }
            },
            linkToDetail(row){
                if(row.userName == this.user.name) {
                    let data = {
                        id: row.customerId,
                        customerContactId: row.userId,
                        name: row.customerName
                    };
                    let arr = this.customerDetailList;
                    for(let i=arr.length-1;i>=0;i--){
                        if(arr[i].id == data.id){
                            arr.splice(i,1);
                            break
                        }
                    }
                    arr.push(data);
                    this.$store.commit('CHANGECUSTOMERDETAIL',{data:arr});
                    this.$router.push({path: '/customer/detail?id=' + row.customerId + '&customerContactId=' + row.userId + '&from=index&customerName=' + row.customerName})
                }
            },
            callContact(row) {
                if(this.calling){
                    return false
                }
                this.$store.dispatch('callCustomer',{calledNum: row.callerNum,customerId: row.id,uuId: this.user.id,deptCode: this.user.departmentId})
                    .then((res)=>{
                        if(!res){return}
                        if(res.data.code == 0) {
                            this.calling = true;
                            axios.get('http://127.0.0.1:3366/callout?phone='+row.callerNum+'&callback=cb_callout&recordId='+res.data.data.id,{});
                            this.getCallStatus()
                        }else{
                            Message.error('拨打电话失败！' + res.data.message);
                        }
                    })
            },
            callHang() {
                this.calling = false;
                axios.get('http://127.0.0.1:3366/callhang?callback=cb_callout',{})
            },
            //获取实时状态
            getCallStatus() {
                axios.get('http://127.0.0.1:3366/callstatus?callback=cb_callout&newcall=0',{})
                    .then((res) => {
                        if(!res){return}
                        let info =  JSON.parse(res.data.split('(')[1].split(')')[0]).Info;
                        if(info.phoneStatus != 'callover'){
                            setTimeout(()=>{
                                this.getCallStatus()
                            },2000)
                        }else {
                            this.calling = false;
                        }
                    })
            },
            clearFilter() {
                this.filter = {
                    levels: [],
                    times: null,
                    dateRange: [],
                    currentPage: 1,
                    pageSize:50
                },
                this.category.name = '';
                this.setFilterCookie();
            },
            missedCallSearch() {
                this.setFilterCookie();
                this.$store.dispatch('missedCall',this.missedCallParams)
                    .then((res)=>{
                        if(!res){return}
                        if(res.data.code == 0) {
                            this.missedCall = res.data.data.list || [];
                            this.filter.currentPage = res.data.data.pageNum || 1;
                            this.filter.pageSize = res.data.data.pageSize || 10;
                            this.total = res.data.data.total || 0;
                        }
                    })
            }

        },
        created () {
            if(process.BROWSER_BUILD){
                this.user = JSON.parse(Cookie.get('userData'));

                let filter = this.$store.getters.missedCallFilter
                let user = this.$store.getters.missedCallUser;
                let category = this.$store.getters.missedCallCategory;
                
                if(filter) this.filter = JSON.parse(filter);
                if(user) this.user = JSON.parse(user);
                if(category) this.category.name = JSON.parse(category);
                this.missedCallSearch();
                //pageTab
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
            // 获取客户类别等级列表
            this.$store.dispatch('getSalesCategoryList')
                .then((response) => {
                    if(!response){return}
                    if(response.data && response.data.data ){
                        var data = response.data.data;
                        this.category.data[0].children=[];
                        for(var i=0;i< data.length;i++){
                            this.category.data[0].children.push({id: data[i].key , label : data[i].value});
                        }
                    }
                })
        },
        mounted(){
            

        }
    }

</script>

<style scoped lang="scss">
    .mc-wrapper{
        min-height: 90%;
        padding-top: 20px;
        .department-tree-select{
            width: 250px;
        }
        .calling,.call-hang{
            display: none;
        }
        .calling + .call-hang{
            display: inline-block;
        }
        .colorBlue{
            cursor: pointer;
            color: #20a0ff;
        }
    }
    .pagination-bar{
        padding: 15px 0;
    }
</style>